package cn.jsp.dao;

import cn.jsp.domain.Stu;
import cn.jsp.jdbc.GeneralRowProcessor;
import cn.jsp.jdbc.RowProcessor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@Repository
public class BaseDao<T> {
  @Autowired
  DataSource dataSource;
  @SneakyThrows
  public List<T> query(String sql, RowProcessor<T> rowProcessor, Object...params) {
    List<T> res=new ArrayList<>();
    try (
            Connection connection = dataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select * from stu");
            ResultSet rs = preparedStatement.executeQuery();) {
      while (rs.next()) {
        T obj=rowProcessor.process(rs);
        res.add(obj);
      }
    }
    return res;
  }
  @SneakyThrows
  public List<T> find(String sql, Class<T> target,Object...params) {
    List<T> res=new ArrayList<>();
    RowProcessor<T> rowProcessor=new GeneralRowProcessor<>(target);
    try (
            Connection connection = dataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select * from stu");
            ResultSet rs = preparedStatement.executeQuery();) {
      while (rs.next()) {
        T obj=rowProcessor.process(rs);
        res.add(obj);
      }
    }
    return res;
  }
}
